package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.hosp.globalexp.YyghException;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.mapper.PaymentInfoMapper;

import com.atguigu.yygh.order.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
    @Autowired
    OrderInfoMapper orderInfoMapper;
    @Override
    public void createPaymentInfo(Long orderId) {
        //判断该订单的支付记录是否存在,如果不存在就创建一个支付记录
        //先查询该订单对应的支付记录,可以根据order_id去支付记录表中查询
        //也可以使用out_trade_no(订单和支付记录的out_trade_no是一致的,并且唯一的)
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        if(paymentInfo==null){
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            paymentInfo=new PaymentInfo();


            //为支付记录赋默认值
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(PaymentTypeEnum.WEIXIN.getStatus());

        //    paymentInfo.setTradeNo();  等支付成功后,微信端返回的transaction_id赋值给tradeNo
         //   paymentInfo.setCallbackTime();
          //  paymentInfo.setCallbackContent();

            paymentInfo.setTotalAmount(orderInfo.getAmount());
            String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")+"|"+orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle();
            paymentInfo.setSubject(subject); //2021-0808|北京协和医院|多发性硬化专科门诊|副主任医师

            paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());//1 支付中 2 已支付
            paymentInfo.setCreateTime(new Date());
            paymentInfo.setUpdateTime(new Date());

            int insert = baseMapper.insert(paymentInfo);
            if(insert<=0){
                throw new YyghException(20001,"支付记录创建失败");
            }
        }
    }

    @Override
    public PaymentInfo getByOrderId(Long orderId) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        return paymentInfo;
    }
}
